#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_sntp.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_wpa2.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <stdlib.h>
#include <string.h>


#include "sgf_time.h"

static const char* TAG = "wifi";

int sgf_time_get(sgf_info_t* info)
{
    ESP_LOGI(TAG, "Initializing SNTP");
    setenv("TZ", "CST-8", 1);
    tzset();
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "cn.pool.ntp.org"); // 中国区NTP服务的虚拟集群
    sntp_setservername(1, "210.72.145.44"); // 国家授时中心服务器 IP 地址
    sntp_setservername(2, "ntp1.aliyun.com");
    sntp_setservername(3, "1.cn.pool.ntp.org");
    sntp_init();

    time_t now = 0;
    struct tm timeinfo = { 0 };
    int retry = 0;
    const int retry_count = 3;
    while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
        ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
        vTaskDelay(2000 / portTICK_PERIOD_MS);
    }
    // if (retry_count <= 0) {
    //     return -1;
    // }
    time(&now);
    localtime_r(&now, &timeinfo);
    ESP_LOGI(TAG, "year=%d, m=%d, wday=%d, hour=%d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_wday, timeinfo.tm_hour);
    info->year = timeinfo.tm_year + 1900;
    info->wday = timeinfo.tm_wday;
    info->mon = timeinfo.tm_mon + 1;
    info->mday = timeinfo.tm_mday;
    return 0;
}